<template>
  <div>
    <van-nav-bar
      title="城市列表"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
      style="backgroundcolor: #c8bdcb; color: #ffffff"
    />
    <van-index-bar :index-list="indexList">
      <van-index-anchor index="#">当前城市 </van-index-anchor>
      <van-cell :title="city.name" @click="choose" />

      <van-index-anchor index="热">热门城市 </van-index-anchor>
      <van-cell
        :title="item.label"
        v-for="(item, index) in hotCityList"
        :key="index"
        @click="chooseHot(index)"
      />

      <!-- 城市列表 -->
      <div v-for="(value, name) in cityList" :key="name">
        <van-index-anchor :index="name">{{ name }} </van-index-anchor>
        <van-cell
          v-for="(item, index) in value"
          :key="index"
          @click="chooseCity"
          :title="item.label"
        >
        </van-cell>
      </div>
    </van-index-bar>
  </div>
</template>
<script>
import { hotCityApi, getCityApi } from "@/api";
export default {
  name: "",
  data() {
    return {
      indexList: [
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z",
      ],
      city: {
        name: this.$store.state.cityName,
      },
      hotCityList: [],
      cityList: [],
    };
  },
  components: {},
  computed: {},
  methods: {
    chooseHot(index) {
      const res = this.hotCityList[index];
      console.log(res);
      this.$store.commit("SET_PARMAS_CITYID", res.value);
      this.$store.commit("SET_PARMAS_CITYNAME", res.label);
      this.$router.push({
        path: "/layout/search",
      });
      // console.log(this.city);
    },
    choose() {
      // console.log(this.city);
      this.$router.push({
        path: "/layout/search",
        query: {
          city: this.city,
        },
      });
    },
    chooseCity() {
      this.$toast.fail("当前城市暂无房源");
    },
  },
  async created() {
    this.city.name = this.$route.query.city;
    const res = await hotCityApi();
    //  console.log(res);
    this.hotCityList = res.data.body;

    const res2 = await getCityApi(1);
    this.cityList = res2.data.body;

    let newCityList = {};
    //循环26个字母
    this.indexList.forEach((item) => {
      newCityList[item] = [];
      this.cityList.forEach((ele) => {
        //判断开头字母是不是相同
        let first = ele.pinyin.substring(0, 1).toUpperCase();
        if (first == item) {
          newCityList[item].push(ele);
        }
      });
    });
    console.log(newCityList);
    this.$nextTick(() => {
      this.cityList = newCityList;
    });
  },
};
</script>
<style lang="" scoped></style>
